package com.happly.happlycloud.service.impl;

import com.happly.happlycloud.dao.PaperDetailMapper;
import com.happly.happlycloud.dao.PaperMapper;
import com.happly.happlycloud.dao.QuestionMapper;
import com.happly.happlycloud.pojo.Paper;
import com.happly.happlycloud.pojo.PaperDetail;
import com.happly.happlycloud.pojo.Question;
import com.happly.happlycloud.service.QuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@Service("iQuestionService")
public class QuestionServiceImpl implements QuestionService {

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private PaperMapper paperMapper;

    @Autowired
    private PaperDetailMapper paperDetailMapper;


    public ArrayList<Question> findQuestion(int stateId) {
        //随机抽取试题,不能重复
        //满分100分
        //难度系数比例相同
        //当前阶段的所有试题
        List<Question> list= questionMapper.findQuestionByState(stateId);
        //分析：
        //按照难度系数和满分，分析出各个比例抽取试题的题数
        //1-4   2-6  3-8  4-10
        //1-10-40    2-4-24   3-2-16    4-2-20
        //存放已经抽取的试题
        ArrayList<Question> seletList=new ArrayList<Question>();
        //1-10-40
        this.randomSelectQuestion(list,seletList,1,10);
        //2-4-24
        this.randomSelectQuestion(list,seletList,2,4);
        //3-2-16
        this.randomSelectQuestion(list,seletList,3,2);
        //4-2-20
        this.randomSelectQuestion(list,seletList,4,2);
        return seletList;
    }

    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.REPEATABLE_READ)//savePage方法必须使用一个事务：如果有就加入当前事务，如果没有事务就新建事务
    public int savePaper(Paper paper, List<PaperDetail> list,List<Question> answerList) {
        //判断总分
        //1、插入试卷主表
        //2、查询插入主表后生成的主键
        //3、批处理查询试卷从表
        //4、在同一事务内完成

        //调用计算总分方法
        int totalScore=comScore(list,answerList);
        paper.setTotalScore(totalScore);
        //插入试卷主表
        int paperResult=paperMapper.addPaper(paper);
        //需要获取到插入试卷主表所生成的id主键
        //id 自增，第一次插入1   第二2  第三3
        //不能通过独立的查询来获取生成的主键id,因为获取的可能不是自己的

        //获取试卷编号，在插入试卷表后获取
        //设置了使用自动生成主键后，paper对象的id属性就已经存储了生成的主键

        //插入试卷从表
        int paperDetailResult=addPaperDetail(paper.getId(),list);
        if(paperResult==1 && paperDetailResult==list.size()){
            return totalScore;
        }else {
            return -1;
        }
    }
    //插入试卷从表方法
    @Transactional(propagation = Propagation.REQUIRED)
    public int addPaperDetail(int paperId,List<PaperDetail> list){
        //方案1：在数据库端通过PL/SQL的存储过程完成
        //方法2：mybatis的批处理完成
        //方案3：写入到Resis,通过MQ双写一致性写入数据库
        //方案4：逐一完成：耗费的时间比函数或较长
        int result=0;
        //通过循环插入试卷从表
        for (PaperDetail paperDetail : list){
            paperDetail.setPaperId(paperId);
            result+= paperDetailMapper.addPaperDetail(paperDetail);
        }
        return result;
    }
    //计算总分数的方法
    public int comScore(List<PaperDetail> list,List<Question> answerList){
        int totalScore=0;
        for (PaperDetail paperDetail : list){
            for (Question question:answerList){
                if(paperDetail.getQuestionId().equals(question.getId())){
                    if(paperDetail.getUserAnswer().equals(question.getCorrent())){
                        System.out.println(paperDetail.getQuestionId());
                        System.out.println(question.getScore());
                        totalScore=totalScore+question.getScore();
                       // break;
                    }
                }
            }
        }
        return totalScore;
    }

    //根据参数抽取试题
    //param1:该阶段的所有试题
    //param2:存放抽取到的试题
    //param3:抽取试题的难度系数
    //param4:抽取试题的个数
    private void randomSelectQuestion(List<Question> list,ArrayList<Question> selectList,
                                      int levelId,int selectCount){
        Random random=new Random();
        //抽取试题的个数
        int count=0;
        while (true){
            if(list.size()==0){
                break;
            }
            //产生随机数 random.netxInt(大数-小数+1)+小数
            int index=random.nextInt(list.size());

            Question question=list.get(index);
            if(levelId==question.getLevelId()){
                //添加到存放抽取试题的集合中
                selectList.add(question);
                count++;
                //从集合中删除
                list.remove(index);

            }
            if(count==selectCount){
                break;
            }
        }
    }
}
